package org.mseco.doc.expensetrack;

import java.util.Calendar;
import java.util.List;

import org.mseco.doc.expensetrack.dao.Transaction;
import org.mseco.doc.expensetrack.dao.TransactionDataSource;
import org.mseco.doc.expensetrack.util.CalendarUtil;
import org.mseco.doc.expensetrack.util.FormatUtil;
import org.mseco.doc.expensetrack.util.LayoutUtil;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;

public class ListTransactions extends Activity {

	private TransactionDataSource transactionDataSource;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_list_transactions);
		populateView();
	}

	public void populateView() {
		TableLayout tableLayout = (TableLayout) findViewById(R.id.transactionTable);
		tableLayout.removeAllViews();

		List<Transaction> transactions = getTransactionDataSource().findAll();
		long total = 0;
		long totalLast7Days = 0;
		long totalThisWeek = 0;
		long totalThisMonth = 0;
		long totalLast30Days = 0;
		long totalPreviousMonth = 0;

		Calendar today = Calendar.getInstance();
		Calendar weekStart = CalendarUtil.getStartOfWeek(today);
		Calendar days7InPast = CalendarUtil.get7DaysInThePast(today);
		Calendar days30InPast = CalendarUtil.get30DaysInThePast(today);
		Calendar monthStart = CalendarUtil.getStartOfMonth(today);
		Calendar[] lastMonth = CalendarUtil.getPreviousMonth(today);

		int counter = 0;
		long counterTotal = 0;
		for (Transaction transaction : transactions) {

			Calendar transactionDate = Calendar.getInstance();
			transactionDate.setTime(FormatUtil.stringToDate(transaction
					.getDate()));

			transactionDate.setFirstDayOfWeek(Calendar.MONDAY);

			if (transactionDate.after(weekStart)) {
				totalThisWeek += transaction.getValue();
			}
			if (transactionDate.after(days7InPast)) {
				totalLast7Days += transaction.getValue();
			}
			if (transactionDate.after(days30InPast)) {
				totalLast30Days += transaction.getValue();
			}
			if (transactionDate.after(monthStart)) {
				totalThisMonth += transaction.getValue();
			}
			if (transactionDate.after(lastMonth[0])
					&& transactionDate.before(lastMonth[1])) {
				totalPreviousMonth += transaction.getValue();
			}
			total += transaction.getValue();

			TableRow tableRow = new TableRow(this);
			tableRow.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
			tableLayout.addView(tableRow);

			TextView id = new TextView(this);
			LayoutUtil.setupTextViewinRow(id, this, Gravity.LEFT);
			id.setText(transaction.getId() + "");
			tableRow.addView(id);

			TextView value = new TextView(this);
			LayoutUtil.setupTextViewinRow(value, this, Gravity.RIGHT);
			value.setText(FormatUtil.format(transaction.getValue()));
			tableRow.addView(value);

			TextView date = new TextView(this);
			date.setText(transaction.getDate() + "");
			LayoutUtil.setupTextViewinRow(date, this, Gravity.LEFT);
			tableRow.addView(date);

			TextView type = new TextView(this);
			type.setText(transaction.getTypeAsString() + "");
			LayoutUtil.setupTextViewinRow(type, this, Gravity.LEFT);
			tableRow.addView(type);

			TextView location = new TextView(this);
			LayoutUtil.setupTextViewinRow(location, this, Gravity.LEFT);
			location.setText("Location");
			final String[] loc = transaction.getLocation().split("-");
			final Activity mContext = this;
			location.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View source) {
					Uri location = Uri.parse("geo:" + loc[0] + "," + loc[1]
							+ "?z=14");
					Intent mapIntent = new Intent(Intent.ACTION_VIEW, location);
					mContext.startActivity(mapIntent);
				}

			});
			tableRow.addView(location);

			Button button = new Button(this);
			button.setText("Delete");
			// button.setBackgroundResource(R.drawable.cellshape);
			button.setOnClickListener(new MyClickListener(transaction,
					transactionDataSource, this));
			button.setMaxHeight(20);
			tableRow.addView(button);

			counter++;
			counterTotal += transaction.getValue();

			if (counter % 7 == 0) {
				// place a red line and the total for those days
				View view = new View(this);
				view.setMinimumHeight(2);
				view.setBackgroundColor(0xFF0000);
				tableLayout.addView(view);

				TableRow row = new TableRow(this);

				TextView textView = new TextView(this);
				textView.setText(this.getResources().getText(R.string.total));
				LayoutUtil.setupTextViewinRow(textView, this, Gravity.RIGHT);
				row.addView(textView);

				textView = new TextView(this);
				textView.setText(FormatUtil.format(counterTotal));
				LayoutUtil.setupTextViewinRow(textView, this, Gravity.RIGHT);
				row.addView(textView);
				tableLayout.addView(row);
				
				textView = new TextView(this);
				LayoutUtil.setupTextViewinRow(textView, this, Gravity.RIGHT);
				row.addView(textView);

				view = new View(this);
				view.setMinimumHeight(2);
				view.setBackgroundColor(0xFF0000);
				tableLayout.addView(view);

				counterTotal = 0; // reset
			}
		}
		{
			TableRow row = new TableRow(this);

			TextView textView = new TextView(this);
			LayoutUtil.setupTextViewinRow(textView, this, Gravity.RIGHT);
			textView.setText(this.getResources().getText(R.string.total));
			row.addView(textView);

			textView = new TextView(this);
			textView.setText(FormatUtil.format(counterTotal));
			LayoutUtil.setupTextViewinRow(textView, this, Gravity.RIGHT);			
			row.addView(textView);
			
			textView = new TextView(this);
			LayoutUtil.setupTextViewinRow(textView, this, Gravity.RIGHT);
			row.addView(textView);
			
			tableLayout.addView(row);
		}

		TextView textView = (TextView) findViewById(R.id.totalThisWeek);
		textView.setText(FormatUtil.format(totalThisWeek));
		textView = (TextView) findViewById(R.id.totalThisMonth);
		textView.setText(FormatUtil.format(totalThisMonth));
		textView = (TextView) findViewById(R.id.totalLastMonth);
		textView.setText(FormatUtil.format(totalPreviousMonth));
		textView = (TextView) findViewById(R.id.last7Days);
		textView.setText(FormatUtil.format(totalLast7Days));
		textView = (TextView) findViewById(R.id.last30Days);
		textView.setText(FormatUtil.format(totalLast30Days));
		textView = (TextView) findViewById(R.id.total);
		textView.setText(FormatUtil.format(total));
	}

	@Override
	protected void onResume() {
		populateView();
		super.onResume();
	}

	public TransactionDataSource getTransactionDataSource() {
		if (transactionDataSource == null) {
			transactionDataSource = new TransactionDataSource(this);
			transactionDataSource.open();
		}
		return transactionDataSource;
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (getTransactionDataSource() != null) {
			getTransactionDataSource().close();
		}
	}

	class MyClickListener implements OnClickListener {

		private Transaction transaction;
		private TransactionDataSource transactionDataSource;
		private Activity context;

		public MyClickListener(Transaction transaction,
				TransactionDataSource transactionDataSource, Activity context) {
			this.transaction = transaction;
			this.transactionDataSource = transactionDataSource;
			this.context = context;
		}

		@Override
		public void onClick(View v) {

			AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);

			// Setting Dialog Title
			alertDialog.setTitle("Warning !");

			// Setting Dialog Message
			alertDialog.setMessage("Are you sure you want to delete record: "
					+ transaction);

			// On pressing Settings button
			alertDialog.setPositiveButton("ok",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							transactionDataSource.delete(transaction);
							ListTransactions.this.populateView();
						}
					});

			// on pressing cancel button
			alertDialog.setNegativeButton("Cancel",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});

			// Showing Alert Message
			alertDialog.show();

		}
	}
}
